import { useState, useEffect } from "react";
import { useModel } from "umi";
import { Form, Input, Select, Button, message, Space, Cascader, Row, Col } from "antd";
import { useReactive } from "ahooks";

import useStaff from "../../hooks/staff/useStaff";
import userCheckInstitutionNameNoSelf from "../../hooks/institution/userCheckInstitutionNameNoSelf";
import useUpdateInstitution from "../../hooks/institution/useUpdateInstitution";

const EditInstitutionForm = ({ institution, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");

    const { loading: staffLoading, staffs } = useStaff({});

    const { checkInstitutionNameNoSelf } = userCheckInstitutionNameNoSelf();
    const { updateInstitution } = useUpdateInstitution();

    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
        maInfo: institution.maInfo || {},
        asInfo: institution.asInfo || {},
    });

    let onFinish = async (values) => {
        values.oiUuid = institution.oiUuid;
        values.maInfo = state.maInfo || {};
        values.asInfo = state.asInfo || {};

        let res = await updateInstitution(values);

        if (res) {
            form.resetFields();
            message.success("成功更新兴趣组信息");
            reloadData();
            onCloseGlobalModal();
        }
    };

    const oiNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkInstitutionNameNoSelf({ oiName: value, notEqualTo: institution.oiUuid });
            if (res === null) return Promise.reject(`检查兴趣组名称出错`);
            return res > 0 ? Promise.reject(`兴趣组名称重复！`) : Promise.resolve();
        } else {
            return Promise.reject(`兴趣组名称只能输入中文、英文、数字，最多30个汉字`);
        }
    };

    const { oiZoja, maInfo, asInfo } = institution;

    const initialValues = {
        ...institution,
        maInfo: maInfo?.osUuid || undefined,
        asInfo: asInfo?.osUuid || undefined,
        oiZoja: oiZoja.map((item) => item.id),
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} initialValues={initialValues}>
            <Form.Item label={`兴趣组名称`} name="oiName" validateTrigger="onBlur" rules={[{ required: true, validator: oiNameValidator }]}>
                <Input placeholder="请输入" />
            </Form.Item>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="负责人" name="maInfo" rules={[{ required: true }]}>
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.maInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="管理人" name="asInfo">
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.asInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="职能说明" name="oiDesc">
                <Input.TextArea placeholder="请输入" />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.loading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.loading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default EditInstitutionForm;
